<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件代理</title>
  </head>
  <body>
    <style>
      .font-color {
        color: yellow;
      }
    </style>
    <div>
      lee web
      <button data-event="hiden">按钮</button>
      <div data-event="changeBackgroundColor" data-bg-color="red">bigabc.top</div>
      <h2 data-event="toggleClass" data-class="font-color">baidu.com</h2>
      <div style="background-color: blue; width: 200px; height: 200px" data-event="opacity" data-opacity="0.5"></div>
    </div>
    <script>
      //事件代理
      class ProxyEvent {
        constructor(obj, type = 'click') {
          obj.addEventListener(type, (e) => {
            //执行的方法名
            let event = e.target.dataset.event
            if (this[event]) {
              this[event].call(e.target, e)
            }
          })
        }
        opacity(event) {
          let opacity = this.dataset.opacity
          this.style.opacity = opacity
        }
        hiden(event) {
          alert(this.textContent)
        }
        changeBackgroundColor(event) {
          this.style.backgroundColor = this.dataset.bgColor
        }
        toggleClass(event) {
          let className = this.dataset.class
          this.classList.toggle(className)
        }
      }
      new ProxyEvent(document.body, 'click')
    </script>
  </body>
</html>
